<template>
	<view class="login">
		<g-navbar title="登录"></g-navbar>
		<view class="login-title">
			{{isPassword?'密码':"验证码"}}登录后操作
		</view>
		<view class="login-form">
			<uni-forms class="form-main" :modelValue="formData" :rules="rules" ref="loginForm">
				<uni-forms-item class="form-item" label="手机号" name="phone">
					<g-input v-model="formData.phone" type="phone" />
				</uni-forms-item>
				<uni-forms-item class="form-item" label="密码" name="password" v-if="isPassword">
					<g-input v-model="formData.password" type="password" />
				</uni-forms-item>
				<uni-forms-item class="form-item" label="验证码" name="code" v-else>
					<g-input v-model="formData.code" type="code" ref="codeInput" @clickvcode="clickvcode"
						:disabled="!isVcodeDisable" id="login" />
				</uni-forms-item>
			</uni-forms>
			<view class="forget-password-btn-wrapper">
				<view class="forget-password-btn" @click="jump">
					忘记密码<i class="iconfont icon-help icon" />
				</view>
			</view>
		</view>

		<view class="login-btn-wrapper">
			<g-button :btn_text="!isPassword?'验证码登录':'密码登录'" :width="686" :height="104" :fontSize="32"
				@click="clickLogin" />
			<view class="vcode-login-btn" @click="changeLoginType">{{isPassword?'验证码登录':'密码登录'}}</view>
		</view>

		<g-service-terms ref="service" top="81.2%" />
	</view>
</template>

<script lang="ts">
	export default {
		options: {
			styleIsolation: 'shared'
		},
	}
</script>

<script lang="ts" setup>
	import {
		reactive,
		ref,
		Ref,
		computed
	} from "vue";
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app'
	import REST_URL from "@/http/http.restUrl";
	import { useUserData } from '@/hooks/useUserData';
	import { useToken } from '@/hooks/useToken';
	import {FOLLOW_STATUS} from '@/enum/follow';
	import global from '@/global';
	import {VERSION_TYPE} from '@/enum/version';
	import {useStore} from 'vuex';
	
	
	const store = useStore();

	// import type { UniFormsValidateFields } from '@uni-helper/uni-ui-types';



	//服务条款元素
	const service : Ref<IServiceComp> = ref({} as IServiceComp);

	const codeInput : Ref<any> = ref(null);


	//登录方式是否为密码登录
	const isPassword : Ref<boolean> = ref(true);

	type LOGIN_TYPE = 'password' | 'vcode' | null;
	
	
	onLoad((e) => {
		console.log(e);
		const type : LOGIN_TYPE = e ? e.type : 'vcode';
		isPassword.value = type == 'password';
	})



	//改变登录方式
	const changeLoginType = () : void => {
		isPassword.value = !isPassword.value
	}
	//表单元素
	const loginForm : Ref<any> = ref(null);

	//表单数据
	const formData : loginFormData = reactive({
		phone: '',
		password: '',
		code: '',
	});

	//表单验证规则
	let rules = reactive({
		phone: {
			rules: [{
				required: true,
				errorMessage: '请输入手机号码'
			},
			{
				minLength: 11,
				errorMessage: '请输入11位手机号码'
			}
			]
		},
		password: {
			rules: [{
				required: true,
				errorMessage: '请输入密码'
			},
			{
				minLength: 6,
				errorMessage: '密码需要至少6位字符'
			}
			]
		},
		code: {
			rules: [{
				required: true,
				errorMessage: '请输入验证码'
			},
			{
				minLength: 6,
				errorMessage: '请输入6位验证码'
			}
			]
		},
	});

	const isVcodeDisable = computed(() => {
		return formData.phone && formData.phone.length == 11;
	})

	onReady(() => {
		loginForm.value.setRules(rules);
	})



	const clickLogin = () : void => {
		if (!service.value.isAgreeServicTerms) {
			uni.prompt.$showToast('请同意服务条款');
			return
		}
		const vaildList = isPassword.value ? ['phone', 'password'] : ['phone', 'code'];
		loginForm.value.validate(vaildList).then((form : loginFormData) => {
			console.log('表单验证成功：', form);
			login(form)
		}).catch((form : loginFormData) => {
			console.log('表单验证失败：', form);
			// uni.prompt.$showToast('表单验证失败');
		})
	}

	const login = async (form : loginFormData) : Promise<void> => {
		const { setUserLocalLabel, getUserInfo } = useUserData();
		const { setTokenSync } = useToken();
		let options : loginFormData;
		let restUrl = isPassword.value ? REST_URL.loginByPassword : REST_URL.loginByVcode;
		if (isPassword.value) {
			options = {
				phone: form.phone,
				password: form.password
			}
		} else {
			options = {
				phone: form.phone,
				code: form.code
			}
		}
		try{
			const { data } = await uni.http.POST(restUrl, options);
			
			console.log('登录成功===>', data);
			//存储token
			setTokenSync(data.access_token);
			//获取用户信息
			const userInfo = await getUserInfo(data.customer_id);
			
			//设置本地标签
			setUserLocalLabel(data.customer_id);
			//存储用户信息
			uni.store.local('userInfo', userInfo);
			//设置登录状态
			uni.loginManger.$resolve();
			//跳转
			if(data.attention_status == FOLLOW_STATUS.UNFOLLOW){
				uni.router.route('/pages/follow/follow');
			}else{
				if(store.state.version == VERSION_TYPE.EXP_VERSION){
					uni.router.route('/pages/home/home');
				}else{
					uni.router.route('/pages/statistics/statistics');
				}
				// uni.router.route('/pages/home/home');
			}
		}catch(e){
			if(e&&e.status==-4){
				uni.router.route('/pages_login/register/register')
			}
		}
	}





	const clickvcode = async () : Promise<void> => {
		await uni.http.POST(REST_URL.sendCode, {
			phone: formData.phone
		})
		codeInput.value.changeStatus();
		uni.prompt.$showToast('已发送验证码');
	}



	const jump = () : void => {
		uni.router.route('/pages_login/reset_password/resetPassword')
	}
	

</script>

<style scoped lang="scss">
	@import "./login.scss";
</style>